package com.wenx.v3system.modular.platform.controller;

import com.wenx.v3core.response.R;
import com.wenx.v3system.modular.platform.domain.dto.PlatformUserAuthRequestDto;
import com.wenx.v3system.modular.platform.domain.dto.PlatformUserAuthResultDto;
import com.wenx.v3system.modular.platform.service.PlatformUserAuthService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 平台用户认证控制器
 * 提供平台用户认证接口，供auth服务调用
 *
 * @author wenx
 */
@Slf4j
@RestController
@RequestMapping("/api/v3/platform/auth")
@RequiredArgsConstructor
@Tag(name = "平台用户认证", description = "平台用户认证相关接口")
public class PlatformUserAuthController {

    private final PlatformUserAuthService platformUserAuthService;

    /**
     * 平台用户认证接口
     * 接收用户名和密码，进行内部验证，返回认证结果
     *
     * @param request 认证请求参数
     * @return 认证结果
     */
    @PostMapping("/authenticate")
    @Operation(summary = "平台用户认证", description = "验证平台用户的用户名和密码，返回认证结果")
    public R authenticate(@RequestBody @Validated PlatformUserAuthRequestDto request) {
        log.debug("平台用户认证请求: identifier={}", request.getIdentifier());
        
        try {
            PlatformUserAuthResultDto result = platformUserAuthService.authenticate(request);
            
            if (result.getSuccess()) {
                log.info("平台用户认证成功: identifier={}, userId={}", request.getIdentifier(), result.getUserId());
            } else {
                log.warn("平台用户认证失败: identifier={}, reason={}", request.getIdentifier(), result.getFailureReason());
            }
            
            return R.ok(result);
        } catch (Exception e) {
            log.error("平台用户认证异常: identifier={}", request.getIdentifier(), e);
            PlatformUserAuthResultDto failureResult = PlatformUserAuthResultDto.failure("系统异常，请稍后重试");
            return R.ok(failureResult);
        }
    }
}